import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Message, Loading } from 'element-ui'
const baseUrl = process.env.VUE_APP_BASE_API
const mimeMap = {
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    zip: 'application/zip'
}
export async function handleBatchDownload(selectFileList) {
    let loadingInstance = Loading.service({
        lock: true,//lock的修改符--默认是false
        text: 'Loading',//显示在加载图标下方的加载文案
        spinner: 'el-icon-loading',//自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)'//遮罩层颜色
});
    let ids = []
    selectFileList.map(item => {
        ids.push(item.fileurl.split('download/')[1])
    })
    const url = baseUrl + '/api/system/download/getZip'
    axios({
        method: 'post',
        url: url,
        responseType: 'blob',
        data: JSON.stringify(ids),
        headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then(res => {
        console.log(res)
        if (res.data.size === 0) {
            Message.error({ showClose: true, message: '网络异常请稍后再试', type: "error", offset: 200 });
        } else {
            resolveBlob(res, mimeMap.zip,loadingInstance)
        }
    })

}
export function resolveBlob(res, mimeType,loadingInstance) {
   
    const aLink = document.createElement('a')
    var blob = new Blob([res.data], { type: mimeType })
    // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    var contentDisposition = decodeURI(res.headers['content-disposition'])
    var result = patt.exec(contentDisposition)
    var fileName = result[1]
    fileName = fileName.replace(/\"/g, '')
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', fileName) // 设置下载文件名称
    document.body.appendChild(aLink)
    aLink.click()
    document.body.appendChild(aLink)
    loadingInstance.close();
}

// export async function handleBatchDownload(selectFileList) {

//     const data = selectFileList;
//     const zip = new JSZip()
//     const cache = {}
//     const promises = []
//     var fileNames = []
//     // let loadingInstance = Loading.service({ fullscreen: true, text: '下载中', lock: true, });
//     await data.forEach((item, index) => {
//         console.log(item, 'item')
//         const promise = getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
//             // let arr_type = data.headers['content-disposition'].split(".") //获取格式
//             // const arr_name = item.split("."); //截取文件名
//             // let file_name = arr_name[arr_name.length - 1] + '.' + arr_type[arr_type.length - 1].replace("\"", "") // 获取文件名
//             if (fileNames.length > 0) {
//                 if (fileNames.indexOf(item.fileName) > -1) {
//                     var lastIndex = item.fileName.lastIndexOf(".");
//                     item.fileName = item.fileName.substring(0, lastIndex) + "(1)" + item.fileName.substring(lastIndex);
//                 }
//             } else {
//                 fileNames.push(item.fileName);
//             }
//             zip.file(item.fileName, data.data, {
//                 binary: true
//             }) // 逐个添加文件
//             cache[item.fileName] = data.data
//             // setTimeout(() => {
//             //     loadingInstance.close();
//             // }, 2000);

//         })
//         promises.push(promise)
//     })
//     Promise.all(promises).then(() => {
//         zip.generateAsync({
//             type: "blob"
//         }).then(content => { // 生成二进制流
//             saveAs(content, "templateDownload.zip") // 利用file-saver保存文件
//         })

//     })
// }

// export function getFile(item) {
//     let vm = this;
//     var url = baseUrl + item.fileurl
//     return new Promise((resolve, reject) => {
//         axios({
//             method: 'get',
//             url,
//             responseType: 'arraybuffer',
//             headers: { 'Authorization': 'Bearer ' + getToken() }
//         }).then(res => {
//             console.log(res, 'res')
//             if (res.headers['accept-ranges']) {

//                 resolve(res)
//             } else {
//                 Message.error({ showClose: true, message: item.fileName + '文件不存在', type: "error", offset: 200 });
//             }
//         }).catch(error => {
//             reject(error.toString())
//         })
//     })
// }